package com.yanchangapp.ui.activity.mail;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.util.ui.UIUtils;
import com.yanchangapp.R;
import com.yanchangapp.adapter.CntDpAdapter;
import com.yanchangapp.adapter.CntSheepAdapter;
import com.yanchangapp.commom.AppConstant;
import com.yanchangapp.model.bean.CntUserBean;
import com.yanchangapp.model.bean.MailUserBean;
import com.yanchangapp.model.response.CntListResponse;
import com.yanchangapp.ui.presenter.ContactAtPresenter;
import com.yanchangapp.ui.view.ContactAtView;
import com.zxl.baselib.widget.TipDialog;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;

/**
 *
 * 邮件 --
 *     联系人选择页面,新增返回确认...
 *     联系人选择页面可以告一段落了...
 *
 */

public class ContactSelectActivity extends BaseActivity<ContactAtView, ContactAtPresenter> implements ContactAtView, CntDpAdapter.CntSelectListener {
    @BindView(R.id.ivToolbarNavigation)
    ImageView ivToolbarNavigation;
    @BindView(R.id.vToolbarDivision)
    View vToolbarDivision;
    @BindView(R.id.tvToolbarTitle)
    TextView tvToolbarTitle;
    @BindView(R.id.rvSheep)
    RecyclerView rvSheep;
    @BindView(R.id.rvDepartments)
    RecyclerView rvDepartments;
    @BindView(R.id.btnEnsure)
    Button mBtnEnsure;
    @BindView(R.id.chCheckAll)
    CheckBox mCheckboxAll;
    @BindView(R.id.checkLinear)
    LinearLayout mCheckLinear;
    @BindView(R.id.llContent)
    LinearLayout llContent;
    @BindView(R.id.frameProgress)
    RelativeLayout frameProgress;
    @BindView(R.id.btnNextRefresh)
    TextView btnNextRefresh;
    @BindView(R.id.llErrorNetwork)
    LinearLayout llErrorNetwork;
    // 如果这样做还是不行的...
    private List<CntUserBean> mSheepBeanList;
    // 头部面包屑  Adapter
    private CntSheepAdapter mCntSheepAdapter;
    // 部门       Adapter
    private CntDpAdapter mCntDpAdapter;
    // 当前部门的数据     列表
    private List<CntUserBean> mCntDpUserList;

    // 原始数据Bean
    private CntUserBean mOriginBean;
    private int mCurrentIndex;
    private List<MailUserBean> mSelectLists;

    private static final String TAG = "Contact";
    // 来源
    private static final String ORIGIN = "origin";
    // 数据返回
    public static final String DATA_BACK = "data_back";
    // 从收件人传递
    public static final int RCODE_RECEIVER = 101;
    // 从抄送人传递
    public static final int RCODE_COPY = 102;

    private Dialog mQuitDialog;

    public static void show(Activity mActivity,int requestCode){
        Intent intent = new Intent(mActivity,ContactSelectActivity.class);
        mActivity.startActivityForResult(intent,requestCode);
    }

    @Override
    protected void init() {
        mSheepBeanList = new ArrayList<>();
        mCntDpUserList = new ArrayList<>();
        // 选中的数量
        mSelectLists = new ArrayList<>();
    }


    @Override
    protected int provideContentViewId() {
        return R.layout.activity_contact_select;
    }

    @Override
    protected ContactAtPresenter createPresenter() {
        return new ContactAtPresenter(this);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        // 设置标题
        tvToolbarTitle.setText("选择联系人");
        showLoading();
        setHeadAdapter();
        setUserAdapter();
    }


    private void showContent(){
        if (frameProgress.getVisibility() == View.VISIBLE){
            frameProgress.setVisibility(View.GONE);
        }

        if (llContent.getVisibility() == View.GONE){
            llContent.setVisibility(View.VISIBLE);
        }

        if (llErrorNetwork.getVisibility() == View.VISIBLE){
            llErrorNetwork.setVisibility(View.GONE);
        }
    }

    private void showErr(){
        if (frameProgress.getVisibility() == View.VISIBLE){
            frameProgress.setVisibility(View.GONE);
        }

        if (llContent.getVisibility() == View.VISIBLE){
            llContent.setVisibility(View.GONE);
        }

        if (llErrorNetwork.getVisibility() == View.GONE){
            llErrorNetwork.setVisibility(View.VISIBLE);
        }
    }

    private void showLoading(){
        if (frameProgress.getVisibility() == View.GONE){
            frameProgress.setVisibility(View.VISIBLE);
        }

        if (llContent.getVisibility() == View.VISIBLE){
            llContent.setVisibility(View.GONE);
        }

        if (llErrorNetwork.getVisibility() == View.VISIBLE){
            llErrorNetwork.setVisibility(View.GONE);
        }
    }

    private void setHeadAdapter() {
        rvSheep.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
        mCntSheepAdapter = new CntSheepAdapter(R.layout.item_contact_head_sheep,mSheepBeanList);
        rvSheep.setAdapter(mCntSheepAdapter);
    }

    // 初始化用户信息的Adapter
    private void setUserAdapter() {
        // 部门
        LinearLayoutManager mLlDpManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        mLlDpManager.setSmoothScrollbarEnabled(true);
        mLlDpManager.setAutoMeasureEnabled(true);
        rvDepartments.setHasFixedSize(true);
        rvDepartments.setNestedScrollingEnabled(false);
        rvDepartments.setLayoutManager(mLlDpManager);
        mCntDpAdapter = new CntDpAdapter(R.layout.item_contact_dp,mCntDpUserList,this);
        rvDepartments.setAdapter(mCntDpAdapter);
    }


    private void titleScrollToPosition(){
        Log.e(TAG, "标题已经进行了移动了" );
        if (null != mSheepBeanList && mSheepBeanList.size() > 1){
            int index = mSheepBeanList.size() -1;
            rvSheep.scrollToPosition(index);
        }
    }


    @Override
    protected void initData() {
        // 进行数据查询
        showLoading();
        mPresenter.queryMailContactLists();
    }


    @Override
    protected void initListener() {
        ivToolbarNavigation.setOnClickListener(v -> {
            if (mOriginBean == null){
                ContactSelectActivity.this.finish();
                return;
            }

            if (mOriginBean.getSelectedSize() == 0){
                ContactSelectActivity.this.finish();
            }else {
                showQuitDialog();
            }
        });
        // 面包屑点击事件...
        mCntSheepAdapter.setOnItemClickListener((adapter, view, position) -> {
            mCurrentIndex = position;
            if (position != mSheepBeanList.size()-1) {
                // 移除面包屑 并进行刷新
                int size = mSheepBeanList.size() - 1 - position;
                for (int i=0;i<size;i++){
                    mSheepBeanList.remove(mSheepBeanList.size()-1);
                }
                mCntSheepAdapter.notifyDataSetChanged();
                mCntDpUserList.clear();
                mCntDpUserList.addAll(mSheepBeanList.get(position).getChildren());
                // 设置cb是否选中
                mCntDpAdapter.notifyDataSetChanged();
                // 当前条目选中....
                titleScrollToPosition();
                setCheckboxState();
            }
        });

        mCntDpAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.tvDpNext){
                // 展示下一级别的数据,当前的index下标...
                mCurrentIndex = mCurrentIndex +1;
                // 当前的数量....
                CntUserBean cntUserBean = mCntDpUserList.get(position);
                // 展示他的孩子...
                List<CntUserBean> list = cntUserBean.getChildren();
                mCntDpUserList.clear();
                mCntDpUserList.addAll(list);
                mCntDpAdapter.notifyDataSetChanged();
                // 进行设置
                mCheckboxAll.setChecked(cntUserBean.isChecked());
                mSheepBeanList.add(cntUserBean);
                mCntSheepAdapter.notifyDataSetChanged();
                titleScrollToPosition();
            }
        });

        mCntDpAdapter.setOnItemClickListener((adapter, view, position) -> view.findViewById(R.id.cbDp).performClick());

        mBtnEnsure.setOnClickListener(v -> whichChildrenCheck());

        mCheckboxAll.setOnClickListener(v -> {
            checkNode(mSheepBeanList.get(mCurrentIndex),mCheckboxAll.isChecked());
            mCntDpAdapter.notifyDataSetChanged();
        });

        mCheckLinear.setOnClickListener(v -> mCheckboxAll.performClick());
        // 刷新点击事件
        btnNextRefresh.setOnClickListener(v -> {
            showLoading();
            mPresenter.queryMailContactLists();
        });
    }

    private void showQuitDialog() {
        if (mQuitDialog == null){
            mQuitDialog = new TipDialog.Builder(this)
                    .setMessage("确认退出此操作吗？")
                    .setEnsureClickListener(new TipDialog.EnsureClickListener() {
                        @Override
                        public void onEnsureClick(TipDialog tipDialog) {
                            tipDialog.dismiss();
                            ContactSelectActivity.this.finish();
                        }
                    }).build();
        }
        mQuitDialog.show();
    }

    /**
     * 数据选中项
     */
    private void whichChildrenCheck() {
        mSelectLists.clear();
        // 如果选中数量为0 那么直接返回即可
        if (mOriginBean.getSelectedSize() == 0){
            callBackResult();
            return;
        }
        addSelectedLists(mOriginBean);
        callBackResult();
    }

    /**
     * 数据返回
     */
    private void callBackResult(){
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putSerializable(DATA_BACK,(Serializable) mSelectLists);
        intent.putExtras(bundle);
        setResult(RESULT_OK,intent);
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 返回按钮的点击事件...
        if (keyCode == KeyEvent.KEYCODE_BACK){
            // 如果返回的数据list为空则直接返回
            if (mOriginBean == null){
                finish();
                return true;
            }

            // 如果有数据 进行下一步的逻辑处理
            if (mSheepBeanList.size() > 1){
                // 移除最后一个
                mSheepBeanList.remove(mSheepBeanList.size() -1);
                // 当前的条目等于之前条目减少1个
                mCurrentIndex = mCurrentIndex - 1;
                // 获得儿子...
                CntUserBean cntUserBean = mSheepBeanList.get(mCurrentIndex);
                List<CntUserBean> list = cntUserBean.getChildren();
                mCntDpUserList.clear();
                mCntDpUserList.addAll(list);
                mCntDpAdapter.notifyDataSetChanged();
                // 进行设置
                mCheckboxAll.setChecked(cntUserBean.isChecked());
                mCntSheepAdapter.notifyDataSetChanged();
                titleScrollToPosition();
                return false;
            }else {
                finish();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void addSelectedLists(CntUserBean cntUserBean){
        if (cntUserBean.getFlag()
                == AppConstant.FLAG_IS_USER && cntUserBean.isChecked()){
            mSelectLists.add(new MailUserBean(cntUserBean.getAddress(),cntUserBean.getName(),cntUserBean.getUsername()));
        }
        for (int i=0;i<cntUserBean.getChildren().size();i++){
            addSelectedLists(cntUserBean.getChildren().get(i));
        }
    }

    private void setCheckboxState(){
        mCheckboxAll.setChecked(mSheepBeanList.get(mCurrentIndex).isChecked());
    }

    @Override
    public void queryContactsSuccess(CntListResponse cntListResponse){
        mOriginBean = cntListResponse.getData();
        mSheepBeanList.clear();
        mCntDpUserList.clear();
        // 进行初始化的数据...
        setOriginBean(mOriginBean);
        mCurrentIndex = 0;
        mCntDpUserList.addAll(mOriginBean.getChildren());
        mSheepBeanList.add(mOriginBean);
        setButtonText();
        mCntSheepAdapter.notifyDataSetChanged();
        // 进行列表刷新
        mCntDpAdapter.notifyDataSetChanged();
        showContent();
    }

    /**
     * 设置原始数据
     */
    private void setOriginBean(CntUserBean currentBean) {
        for (int i=0;i<currentBean.getChildren().size();i++){
            CntUserBean bean = currentBean.getChildren().get(i);
            bean.setParent(currentBean);
            setOriginBean(bean);
        }
    }

    @Override
    public void queryContactFailure(String err) {
        UIUtils.showToast(err);
        showErr();
    }

    // 按钮切换事件
    @Override
    public void onCheckChangedListener(int position, boolean state,CntUserBean cntUserBean) {
        checkNode(cntUserBean,state);
        mCheckboxAll.setChecked(cntUserBean.getParent().isChecked());
        mCntDpAdapter.notifyDataSetChanged();
    }


    private void checkNode(CntUserBean cntUserBean,boolean isChecked){
        cntUserBean.setChecked(isChecked);
        checkChildren(cntUserBean,isChecked);
        unCheckNode(cntUserBean,isChecked);
        checkedSize(cntUserBean);
        setButtonText();
    }

    private void checkedSize(CntUserBean cntUserBean) {
         // 如果是选中的状态...
         boolean selected = cntUserBean.isChecked();
         if (selected){
             // 设置完全选中数量
             int addSize = cntUserBean.getSum()-cntUserBean.getSelectedSize();
             cntUserBean.setSelectedSize(cntUserBean.getSum());
             // 父亲有问题
             setChangeParentSize(cntUserBean,addSize,cntUserBean.getId());
             setAddChildrenSize(cntUserBean);
         }else {
             // 设置当前选中数量
             cntUserBean.setSelectedSize(0);
             int addSize = cntUserBean.getSelectedSize()-cntUserBean.getSum();
             setChangeParentSize(cntUserBean,addSize,cntUserBean.getId());
             setMinChildrenSize(cntUserBean);
         }

    }

    // 设置子节点数量减少
    private void setMinChildrenSize(CntUserBean cntUserBean) {
        for (int i=0;i<cntUserBean.getChildren().size();i++){
            CntUserBean cntUserBeanInner = cntUserBean.getChildren().get(i);
            cntUserBeanInner.setSelectedSize(0);
            setMinChildrenSize(cntUserBeanInner);
        }
    }

    // 设置子节点数量增加
    private void setAddChildrenSize(CntUserBean cntUserBean) {
        for (int i=0;i<cntUserBean.getChildren().size();i++){
            CntUserBean cntUserBeanInner = cntUserBean.getChildren().get(i);
            cntUserBeanInner.setSelectedSize(cntUserBeanInner.getSum());
            setAddChildrenSize(cntUserBeanInner);
        }
    }

    /**
     * 设置父亲节点数量改变
     * @param cntUserBean
     * @param changeSize
     * @param currentID
     */
    private void setChangeParentSize(CntUserBean cntUserBean,int changeSize,long currentID){
        if (cntUserBean.getId() != currentID){
            cntUserBean.setSelectedSize(cntUserBean.getSelectedSize()+changeSize);
        }
        if (cntUserBean.getParent() != null){
            setChangeParentSize(cntUserBean.getParent(),changeSize,currentID);
        }
    }

    /**
     * 设置子节点的选中状态
     * @param cntUserBean
     * @param isChecked
     */
    private void checkChildren(CntUserBean cntUserBean, boolean isChecked) {
        for (int i=0;i<cntUserBean.getChildren().size();i++){
            cntUserBean.getChildren().get(i).setChecked(isChecked);
            checkChildren(cntUserBean.getChildren().get(i),isChecked);
        }
    }

    /**
     * 设置父节点的选中状态
     * @param n
     * @param isChecked
     */
    private void unCheckNode(CntUserBean n, boolean isChecked){
        if (n == null){
            return;
        }
        boolean flag = false;
        // 当前节点设置为true或者false
        n.setChecked(isChecked);
        if(n.getParent() != null ){
            for (int i = 0; i < n.getParent().getChildren().size(); i++) {
                // 除了当前的Item,如果儿子都是true
                // 那么则设置父亲
                // 如果有一个false则不设置
                if((n.getParent().getChildren().get(i)) != null && (n.getParent().getChildren().get(i).getId().intValue())
                        != n.getId() && (!n.getParent().getChildren().get(i).isChecked())){
                    flag = true;
                    break;
                }
            }
            if(!flag) {
                unCheckNode(n.getParent(), isChecked);
            }
        }
    }

    /**
     * 设置选中总数
     */
    private void setButtonText(){
        mBtnEnsure.setText(getString(R.string.person_select_choose,String.valueOf(mOriginBean.getSelectedSize()),
               String.valueOf(mOriginBean.getSum()) ));
    }

}
